<template>
    <el-dialog title="新增公式列" :closeOnClickModal="false" width="70%"
               :visible.sync="dialogVisible" :before-close="closeDialog">
        <el-form  ref="dataForm" :rules="rules" id="dataForm"
                  :model="postForm" label-position="middle"  style="min-width: 500px; ">
            <el-form-item label="新增列名称" prop="name">
                <el-input v-model="postForm.name" placeholder="请输入" style="width: 200px" />
            </el-form-item>
            <div class="math-body">
                <div class="left-block">
                    <el-input
                        placeholder="输入关键字进行过滤"
                        v-model="filterText">
                    </el-input>
                    <el-tree
                        class="filter-tree"
                        :data="treeData"
                        :props="defaultProps"
                        default-expand-all
                        @node-click="nodeClick"
                        :filter-node-method="filterNode"
                        ref="tree">
                    </el-tree>
                </div>
                <div class="right-block">
                    <code-content ref="codeContent"></code-content>
                </div>
            </div>
        </el-form>
        <div slot="footer">
            <el-button @click="closeDialog">取 消</el-button>
            <el-button @click="updateData()" type="primary">保存</el-button>
        </div>
    </el-dialog>
</template>

<script>
    import CodeContent from "./codeContent";
    import {addTableOperation} from '@api/url';
    export default {
        name: "formulaDialog",
        components: {CodeContent},
        data() {
            return {
                title: '',
                postForm:{
                    name:'',
                    formula:'',
                    modelId:'',
                },
                rules:{
                    name:[{ required: true, message: '新增列名称必填', trigger: "blur" }],
                },
                filterText: '',
                treeData: [],
                defaultProps: {
                    children: 'children',
                    label: 'label'
                },
            }
        },
        props: {
            dialogVisible:{//弹窗是否关闭
                type:Boolean,
                default:false,
            },
        },
        watch:{
            dialogVisible(val){
                if(val){
                    //填充树节点数据
                    let fields =sessionStorage.getItem('allFields');
                    let options=[
                        {id: 1, label: '数值字段', children: []},
                        {id: 2, label: '文本字段', children: []},
                        {id: 3, label: '时间字段', children: []},
                    ]
                    if(fields){
                        fields= JSON.parse(fields)||[];
                        this.postForm.modelId=fields[0].modelId;
                        fields.forEach(item=>{
                            let temp={id: item.id, label: item.value}
                            if(item.dataType=="NUMBER"){
                                options[0].children.push(temp)
                            }else if(item.dataType=="DATE"){
                                options[2].children.push(temp)
                            }else{
                                options[2].children.push(temp)
                            }
                        })
                        this.treeData=[...options];
                    }
                    this.$forceUpdate();
                }
            },
            filterText(val) {
                this.$refs.tree.filter(val);
            }
        },
        methods: {
            /**
             * 关闭弹窗
             */
            closeDialog() {
                this.$emit("close");
            },
            nodeClick(res){
              let {id,label}=res;
              if(![1,2,3].includes(id)){
                  this.$refs.codeContent.insertVariable(label);
              }
            },
            updateData(){
                //处理公式---start
                let outputString=this.$refs.codeContent.getValue();//##表id14$$##-$$##名字$$
                let array=JSON.parse(sessionStorage.getItem('allFields'));
                // 创建一个映射对象，用于快速查找替换值
                const map = array.reduce((acc, item) => {
                    acc[item.value] = item.colName;
                    return acc;
                }, {});
                // 替换字符串中的值
                for (const key in map) {
                    let replacement = `##${map[key]}$$`; // 替换格式为 $$$colName$$$
                    outputString = outputString.replace(`##${key}$$`, replacement);
                }
                outputString = outputString.replace(/[#$]/g, '');
                this.postForm.formula=outputString;
                //处理公式---end
                console.log(this.postForm)
                this.$refs["dataForm"].validate((valid) => {
                    if (valid) {
                        this.$http.post(addTableOperation, this.postForm).then(res => {
                            this.$emit("save");
                        })
                    }else{
                        this.$message({type: 'error', message: '校验失败'});
                    }
                });

            },
            filterNode(value, data) {
                if (!value) return true;
                return data.label.indexOf(value) !== -1;
            }
        }
    }
</script>

<style lang="stylus">
.math-body{
    width: 100%;
    display: flex;
    flex:  0 0 auto;
    .left-block{
        width: 240px;
        padding-right 4px
        margin-right 4px
        flex-shrink 0
    }
    .right-block{
        border-radius 6px
        border:1px solid lightgray
        width 100%
    }
}
</style>
